package client

import (
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli/v2"
	"io/ioutil"
	"os"
	"path"
	"text/tabwriter"
	"ycontainer/container"
)

func PsAction(context *cli.Context) error {
	containerRootPath := path.Join(container.YcontainerRoot, "containers")

	files, err := ioutil.ReadDir(containerRootPath)
	if err != nil {
		logrus.Errorf("read dir %s err: %v", containerRootPath, err)
		return err
	}

	if len(files) == 0 {
		return nil
	}

	var records []*container.Record
	for _, file := range files {
		recordFileDir := path.Join(containerRootPath, file.Name(), container.DefaultRecordFileName)

		content, err := ioutil.ReadFile(recordFileDir)
		if err != nil {
			logrus.Errorf("Read file %s err: %v", recordFileDir, err)
		}

		var record container.Record
		if err := json.Unmarshal(content, &record); err != nil {
			logrus.Errorf("json unmarshal err: %v", err)
		}
		records = append(records, &record)
	}

	writer := tabwriter.NewWriter(os.Stdout, 12, 1, 3, ' ', 0)
	fmt.Fprint(writer, "ID\tNAME\tPID\tSTATUS\tCOMMAND\tCREATED\n")
	for _, item := range records {
		fmt.Fprintf(writer, "%s\t%s\t%d\t%s\t%s\t%s\n",
			item.Id,
			item.Name,
			item.Pid,
			item.Status,
			item.StartCmdAndArgs,
			item.CreateTime)
	}
	if err := writer.Flush(); err != nil {
		logrus.Errorf("Flush error %v", err)
	}

	return nil
}
